type SvgContent = {attrs: Record<string, string>, innerHtml: string};

// 用于动态加载并缓存图标
const iconCache = new Map<string, SvgContent>();

export function registerIcon(name: string, svgContent: SvgContent) {
    iconCache.set(name, svgContent);
}

export function getIconSvg(name: string): SvgContent | undefined {
    console.log('getIconSvg', name, iconCache);
    return iconCache.get(name);
}

function extractSvgContent(svg: string): SvgContent | null {
    const div = document.createElement('div');
    div.innerHTML = svg;
    const svgElement = div.querySelector('svg');
    
    if(!svgElement) return null;

    const {width, height, ...restAttrs} = Object.fromEntries(
        Array.from(svgElement.attributes).map(attr => [attr.name, attr.value])
    );

    return {
        attrs: restAttrs,
        innerHtml: svgElement.innerHTML
    }
}

const modules = import.meta.glob('../../icons/_svgs/**/*.svg', { eager: true, query: '?raw' });

for (const path in modules) {
    const name = path.match(/([\w-]+)\.svg$/)?.[1];
    if (name) {
        const svgContent = (modules[path] as any).default;
        const content = extractSvgContent(svgContent);
        if (content) registerIcon(name, content);
    }
}